﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Net;
using System.Text;
using TuyennvLibrary.ServerApi.Models;
using Newtonsoft.Json;
using TuyennvLibrary.Notify;
using TuyennvLibrary.Notify.Android;
using TuyennvLibrary.Notify.IOS;
using TuyennvLibrary.ServerApi.Views;
using TuyennvLibrary.ServerApi.Models;

namespace TuyennvLibrary.ServerApi.Controllers
{
    public class MessageController
    {
        public static string sendMessage(string jsondata, string api_key)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Config.UrlGCM);
                request.Method = "POST";
                request.KeepAlive = false;
                byte[] byteArray = Encoding.UTF8.GetBytes(jsondata);
                request.ContentType = "application/json";
                request.ContentLength = byteArray.Length;
                request.Headers.Add(HttpRequestHeader.Authorization, "key=" + api_key);

                Stream dataStream = request.GetRequestStream();
                dataStream.Write(byteArray, 0, byteArray.Length);
                dataStream.Close();

                WebResponse response = request.GetResponse();
                StreamReader reader = new StreamReader(response.GetResponseStream());
                string responsedata = reader.ReadToEnd();
                reader.Close();
                return responsedata;
            }
            catch (Exception ex)
            {
                return JsonConvert.SerializeObject(new { error = ex.Message });
            }
        }
        public static List<object> getregistration_ids(DataTable dtdevice)
        {
           
            List<object> listregistration_ids = new List<object>();
            if (dtdevice.Rows.Count > 0)
            {
                List<string> listGcmID = new List<string>();
                int pagesize = 1000;
                int pagecount = dtdevice.Rows.Count / pagesize;
                if (dtdevice.Rows.Count % pagesize != 0)
                    pagecount++;
                for (int i = 0; i < pagecount; i++)
                {
                    int from = (i * pagesize) >= dtdevice.Rows.Count ? 0 : i * pagesize;
                    int to = ((i + 1) * pagesize) > dtdevice.Rows.Count ? dtdevice.Rows.Count : (i + 1) * pagesize;
                    for (int j = from; j < to; j++)
                    {
                        string gcmid = dtdevice.Rows[j].GetString(ViewApplicationDevices.COLUMN_GCMID, "");
                        if (!string.IsNullOrEmpty(gcmid))
                        {
                            listGcmID.Add(gcmid);
                        }
                    }
                    if (listGcmID.Count > 0)
                    {
                        listregistration_ids.Add(listGcmID);
                        listGcmID = new List<string>();
                    }
                }
            }
            return listregistration_ids;
        }
        public static NotifyResponse sendMessageAndroidForMultiDevice(string appid, List<object> listRegistration, object data)
        {
            //deviceModel deModel=new deviceModel();
            NotifyResponse notifyResponse = new NotifyResponse();
            try
            {
                Application app = new ApplicationModel().GetByID(appid);
                List<object> listresponse = new List<object>();
                foreach (object item in listRegistration)
                {
                   
                    AndroidNotify notify = new AndroidNotify();
                    notify.ApiKey = app.api_key;
                    notify.Data = data;
                    notify.RegistrationIds = (List<string>)item;
                    notifyResponse.Add(notify.Push());
                    //listresponse.Add(response);
                }
            }
            catch (Exception)
            {
            }
            return notifyResponse;
        }
        public static object sendOneMessage(string appid,string gcmid, object data)
        {
            Application app = new ApplicationModel().GetByID(appid);
            var json = new
            {
                collapse_key = "score_update",
                delay_while_idle = true,
                data = new
                {
                    payload = data
                },
                registration_ids = new String[]{gcmid}
            };
            string jsondata = JsonConvert.SerializeObject(json);
            object response = JsonConvert.DeserializeObject(sendMessage(jsondata, app.api_key));
            return response;
        }
        public static List<List<NotificationPayload>> getPagesPushIOS(DataTable dtdevice, string title, object data)
        {

            List<List<NotificationPayload>> listItems = new List<List<NotificationPayload>>();
            if (dtdevice.Rows.Count > 0)
            {
                List<NotificationPayload> listNotification = new List<NotificationPayload>();
                int pagesize = 1000;
                int pagecount = dtdevice.Rows.Count / pagesize;
                if (dtdevice.Rows.Count % pagesize != 0)
                    pagecount++;
                for (int i = 0; i < pagecount; i++)
                {
                    int from = (i * pagesize) >= dtdevice.Rows.Count ? 0 : i * pagesize;
                    int to = ((i + 1) * pagesize) > dtdevice.Rows.Count ? dtdevice.Rows.Count : (i + 1) * pagesize;
                    for (int j = from; j < to; j++)
                    {
                        string tokenId = dtdevice.Rows[j].GetString(ViewApplicationDevices.COLUMN_GCMID, "");
                        if (!string.IsNullOrEmpty(tokenId))
                        {
                            var payload = new NotificationPayload(tokenId, title, data, 1, "default");
                            listNotification.Add(payload);
                        }
                        
                    }
                    if (listNotification.Count > 0)
                    {
                        listItems.Add(listNotification);
                        listNotification = new List<NotificationPayload>();
                    }
                }
            }
            return listItems;
        }
        public static NotifyResponse sendMessageIOSForMultiDevice(List<List<NotificationPayload>> listPageNotification, string filep12, string pass, int Host)
        {
            List<object> listresponse = new List<object>();
            NotifyResponse responses = new NotifyResponse();
            foreach (List<NotificationPayload> Listitem in listPageNotification)
            {
                IOSNotify notify = new IOSNotify();
                notify.Password = pass;
                notify.FileP12 = filep12;
                notify.ListNotification = Listitem;
                notify.Host = Host;
                responses.Add(notify.Push());
            }
            return responses;
        }
        public static object sendMessageOneIOS(string title, object data, List<NotificationPayload> listPageNotification, string filep12, string pass)
        {
            List<object> listresponse = new List<object>();
            var push = new PushNotification(true, filep12, pass);
            var rejected = push.SendToApple(listPageNotification);
            listresponse.Add(rejected);
            return listresponse;
        }
    }
}